package org.mzyyn.qr.service.auction.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.mzyyn.qr.constants.RedisKeyConstant;
import org.mzyyn.qr.context.UserAuthContext;
import org.mzyyn.qr.dto.goods.GoodsInfoDTO;
import org.mzyyn.qr.dto.goods.PageQueryDTO;
import org.mzyyn.qr.entity.AuctionGoodsPO;
import org.mzyyn.qr.enums.GoodStatusEnum;
import org.mzyyn.qr.mapper.AuctionGoodsMapper;
import org.mzyyn.qr.service.auction.AuctionGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.mzyyn.qr.service.auction.AuctionService;
import org.mzyyn.qr.vo.auction.BidRedisVO;
import org.mzyyn.qr.vo.goods.GoodsInfoVO;
import org.mzyyn.qr.vo.goods.GoodsListVO;
import org.qr.xiaocao.common.enums.CommonResultEnum;
import org.qr.xiaocao.exception.ServiceException;
import org.qr.xiaocao.utils.XcMathUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 拍卖商品表 服务实现类
 * </p>
 *
 * @author lipeng
 * @since 2024-09-23
 */
@Service
public class AuctionGoodsServiceImpl extends ServiceImpl<AuctionGoodsMapper, AuctionGoodsPO> implements AuctionGoodsService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    @Lazy
    AuctionService auctionService;

    @Override
    public Page<GoodsListVO> pageList(PageQueryDTO pageQueryDTO){

        Page<GoodsListVO> res = new Page<>(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());
        if(UserAuthContext.shenheVersionCheck()){
            return res;
        }

        Page<AuctionGoodsPO> page = new Page<>(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());
        LambdaQueryWrapper<AuctionGoodsPO> query = new LambdaQueryWrapper<>();
        query.eq(AuctionGoodsPO::getStatus, GoodStatusEnum.WEIJIESHU.getCode());
        query.orderByAsc(AuctionGoodsPO::getPrice);

        Page<AuctionGoodsPO> listPage = this.page(page,query);
        if(CollUtil.isEmpty(listPage.getRecords())){
            return res;
        }

        List<GoodsListVO> pageRecords = listPage.getRecords().stream().map(v -> {
            GoodsListVO bean = BeanUtil.toBean(v, GoodsListVO.class);
            if (StrUtil.isNotEmpty(bean.getGoodsImgs())) {
                bean.setGoodsImgList(Arrays.asList(bean.getGoodsImgs().split(StrUtil.COMMA)));
            }

            bean.setPrice(
                XcMathUtils.formatAndstripTrailingZeros(
                  StrUtil.toStringOrNull(XcMathUtils.initBigDecimal(v.getPrice()).divide(new BigDecimal(10),1, RoundingMode.HALF_UP))
                ,1)
            );

            //获取最新价格及次数
            Long count = stringRedisTemplate.opsForList().size(RedisKeyConstant.AUCTION_JOIN_RECORD + v.getId());
            BidRedisVO latestPrice = auctionService.getLatestPrice(String.valueOf(v.getId()));
            if( latestPrice != null ){
                bean.setNewPrice(latestPrice.getPrice().intValue());
            }
            if( null != count ){
                bean.setCount(count.intValue());
            }
            return bean;
        }).collect(Collectors.toList());
        res.setRecords(pageRecords)
                .setTotal(listPage.getTotal());

        return res;
    }

    @Override
    public AuctionGoodsPO checkAndGetGoodsById(Long id) {
        if( null == id ){
            throw new ServiceException(CommonResultEnum.DATA_NOT_EXIST.getCode(),"商品不存在");
        }
        AuctionGoodsPO goods = this.getById(id);
        if( null == goods ){
            throw new ServiceException(CommonResultEnum.DATA_NOT_EXIST.getCode(),"商品不存在");
        }

        return goods;
    }

    @Override
    public GoodsInfoVO goodsInfo(GoodsInfoDTO goodsInfoDTO) {
        AuctionGoodsPO auctionGoodsPO = checkAndGetGoodsById(goodsInfoDTO.getGoodsId());

        GoodsInfoVO goodsInfo = BeanUtil.toBean(auctionGoodsPO, GoodsInfoVO.class);
        if (StrUtil.isNotEmpty(goodsInfo.getGoodsImgs())) {
            goodsInfo.setGoodsImgList(Arrays.asList(goodsInfo.getGoodsImgs().split(StrUtil.COMMA)));
        }

        //redis获取结束时间
        goodsInfo.setEndTime(getEndTime(String.valueOf(auctionGoodsPO.getId()),auctionGoodsPO.getEndTime()));
        if( goodsInfo.getEndTime().isAfter(LocalDateTime.now()) ){
            goodsInfo.setStatus(GoodStatusEnum.JIESHU.getCode());
        }
        return goodsInfo;
    }


    @Override
    public LocalDateTime getEndTime(String goodsId, LocalDateTime endTime){
        //如果时间剩下最后5分钟了，延迟时间
        String goodEndTimeRedisKey = RedisKeyConstant.GOODS_END_TIME + goodsId;
        String endTimeRedisVal = stringRedisTemplate.opsForValue().get(goodEndTimeRedisKey);
        if( StrUtil.isEmpty(endTimeRedisVal) ){
            return endTime;
        }

        Instant instant = Instant.ofEpochMilli(Long.parseLong(endTimeRedisVal) * 1000);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }
}
